package com.code.soulnetty.modbus.server;

import com.code.soulnetty.modbus.biz.ModbusCache;
import com.code.soulnetty.modbus.server.handler.ModbusTcpHandler;
import io.netty.channel.ChannelHandler;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;

/**
 * @author lyf
 * @date 2022-12-16 18:21
 */
@Configuration
public class ServerInitConfig {

    @Value("${netty.server.port:8000}")
    private String serverPort;
    @Value("${modbus.transport.type:NIO}")
    private String transportType;

    @Autowired
    private ModbusCache modbusCache;

    @PostConstruct
    public void init() {
        // 实例化业务处理的handler
        ModbusTcpHandler modbusTcpHandler = new ModbusTcpHandler(modbusCache);

        // 创建netty服务
        ModbusServer modbusServer = new ModbusServer(transportType, () -> new ChannelHandler[]{
                        new LengthFieldBasedFrameDecoder(Short.MAX_VALUE, 4, 2),
                        modbusTcpHandler});
        modbusServer.init();

        // 绑定监听的端口
        String[] ports = StringUtils.tokenizeToStringArray(serverPort, ",");
        for (String port : ports) {
            modbusServer.connect(new InetSocketAddress(Integer.parseInt(port)));
        }
    }
}
